from gamebox.decorators import token_auth_required
from gamebox.services.user_service import UserService
from gamebox import response, errorcodes, globals
from datetime import datetime, timedelta
import jwt


def login(params: dict):
    """
    根据账号,密码,验证码登录并生成访问凭据
    :param params:
    :return: 响应状态码
    """
    username = params.get('username')
    password = params.get('password')
    captcha = params.get('captcha')
    user_service = UserService()
    if not user_service.sign_in_password(username, password):
        return response.result(errorcodes.PASSWORD_INVALID)

    access_token = jwt.encode({'some': 'test',
                               'exp': datetime.utcnow() + timedelta(seconds=600)},
                              globals.ACCESS_TOKEN_SECRET, algorithm='HS256')
    return response.success({
        'access_token': access_token.decode('utf-8')
    })


@token_auth_required
def logout():
    # 记录日志
    pass


@token_auth_required
def refresh_token(payload, params):
    print(payload, params)
    return response.success('呵呵')
